package LeetCode;

import Constructs.ListNode;

import java.util.TreeSet;

//
// Created by ✎﹏ℳ๓独赏☆独醉 on 2024/5/2.
//
//https://leetcode.cn/problems/merge-k-sorted-lists/description/
public class 合并K个升序链表 {
    public static void main(String[] args) {
    }
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length == 0)return null;
        ListNode res = lists[0];
        if(lists.length == 1)return res;
        for (int i = 1; i < lists.length; i++) {
            res = mergeTwoLists(res,lists[i]);
        }
        return res;
    }
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode newList = new ListNode(0,null);
        ListNode temp = newList;
        while(list1 != null && list2 != null){
            if(list1.val < list2.val){
                temp.next = list1;
                list1 = list1.next;
            }else {
                temp .next = list2;
                list2 = list2.next;
            }
            temp = temp.next;
        }
        while (list1 != null){
            temp.next = list1;
            list1 = list1.next;
            temp = temp.next;
        }
        while (list2 != null){
            temp.next = list2;
            list2 = list2.next;
            temp = temp.next;
        }
        return newList.next;
    }
}
